package com.aacar.op.utils.web;

import com.aacar.op.utils.Collections3;
import com.aacar.op.utils.Reflections;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class PageUtils {
    private static Logger logger = LoggerFactory.getLogger(PageUtils.class);
    public final static String ASC = "asc";
    public final static String DESC = "desc";

    /**
     * <p>
     * datagrid传过来的分页信息
     * </p>
     *
     * @param request
     * @return
     * @author Gongle
     * @since JDK 1.7
     */
    public static Pageable pageableFromDatagrid(javax.servlet.http.HttpServletRequest request) {
        String _page = StringUtils.defaultString(request.getParameter("page"), "1");
        String _rows = StringUtils.defaultString(request.getParameter("rows"), "10");
        String _sort = request.getParameter("sort");
        String _order = StringUtils.defaultString(request.getParameter("order"), "desc");
        //排序
        List<Sort.Order> orders = null;
        Sort sort = null;
        if (StringUtils.isNotBlank(_sort)) {
            orders = new ArrayList<Sort.Order>();
            String[] sortArr = StringUtils.split(_sort, ",");
            String[] orderArr = StringUtils.split(_order, ",");
            Sort.Direction defalutDir = null;
            for (int i = 0; i < sortArr.length; i++) {

                if (i < orderArr.length) {

                    defalutDir = StringUtils.equalsIgnoreCase(orderArr[i], "desc") ? Sort.Direction.DESC : Sort.Direction.ASC;
                }
                orders.add(new Sort.Order(defalutDir, sortArr[i]));
            }
            if (!orders.isEmpty()) {
                sort = new Sort(orders);
            }
        }
        PageRequest pq = new PageRequest(Integer.valueOf(_page) - 1, Integer.valueOf(_rows), sort);
        logger.trace("分页请求对象:{}", pq);
        return pq;
    }

    public static Pageable pageableFromDateTables(javax.servlet.http.HttpServletRequest request) {

        Integer start = Integer.valueOf(StringUtils.defaultString(request.getParameter("start"), "0")  );
        Integer pageSize = Integer.valueOf(StringUtils.defaultString(request.getParameter("length"), "10"));
        String colIndexStr = request.getParameter("order[0][column]");
        int pageNum = start / pageSize;
        Sort.Direction dir = null;
        Sort.Order order = null;
        Sort sort = null;
        if (StringUtils.isNotBlank(colIndexStr)) {
            int colIndex = Integer.valueOf(colIndexStr);
            dir = StringUtils.equalsIgnoreCase(request.getParameter("order[0][dir]"), "desc") ? Sort.Direction.DESC : Sort.Direction.ASC;
            String sortName = request.getParameter("columns[" + colIndex + "][data]");
            order = new Sort.Order(dir, sortName);
            sort = new Sort(order);
        }

        PageRequest pq = new PageRequest(pageNum, pageSize, sort);
        logger.trace("分页请求对象:{}", pq);
        return pq;
    }

    public static void mergeSort(Map<String, Object> params, Pageable pageable) {
        Sort sort = pageable.getSort();
        if (sort != null) {
            List<Sort.Order> orders = (List<Sort.Order>) Reflections.getFieldValue(sort, "orders");
            if (Collections3.isNotEmpty(orders)) {
                //仅获取第一个分页
                Sort.Order o = orders.get(0);
                String orderByName = o.getProperty();
                String orderByDir = Sort.Direction.DESC.equals(o.getDirection()) ? "DESC" : "ASC";
                params.put("orderByName", orderByName);
                params.put("orderByDir", orderByDir);
                logger.trace("单排序 orderByName:{} , orderByDir:{}", orderByName, orderByDir);
            }

        }
    }
}
